package cn.com.hhrcw.web;

import cn.com.hhrcw.conferenceRoom.entity.ConferenceRoom;
import cn.com.hhrcw.conferenceRoom.service.IConferenceRoomService;
import cn.com.hhrcw.entity.*;
import cn.com.hhrcw.mapstruct.EnInfoConvert;
import cn.com.hhrcw.mapstruct.OpInterviewHistoryConvert;
import cn.com.hhrcw.mapstruct.OpJobConvert;
import cn.com.hhrcw.params.OpInterviewHistoryParams;
import cn.com.hhrcw.params.OpInviewAddParams;
import cn.com.hhrcw.service.*;
import cn.com.hhrcw.sms.service.ISysSmsTemplateService;
import cn.com.hhrcw.utils.EmailUtil;
import cn.com.hhrcw.utils.NewsUtil;
import cn.com.hhrcw.utils.SubjectUtils;
import cn.com.hhrcw.vo.EnInfoVO;
import cn.com.hhrcw.vo.OpInterviewHistoryVO;
import cn.com.hhrcw.vo.OpJobVO;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.base.entity.AttributesValueParams;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
* 职位-面试
*
* @author jiangdong
* @since 2020-10-29
*/
@RestController
@Slf4j
@RequestMapping("/personal/v1/opInterviewHistory")
@Api(tags = "职位-面试")
@Validated
public class OpInterviewHistoryController extends JeecgController<OpInterviewHistory, IOpInterviewHistoryService> {

    @Autowired
    private IOpInterviewHistoryService opnterviewHistoryService;

    @Autowired
    private OpInterviewHistoryConvert opInterviewHistoryConvert;
    @Autowired
    private IOpJobService jobService;
    @Autowired
    private IEnInfoService enInfoService;
    @Autowired
    private NewsUtil newsUtil;
    @Autowired
    private EnInfoConvert enInfoConvert;
    @Autowired
    private OpJobConvert opJobConvert;
    @Autowired
    private ISysSmsTemplateService sysSmsTemplateService;
    @Autowired
    private IPiInfoService piInfoService;
    @Autowired
    private EmailUtil emailUtil;
    @Autowired
    private IEnContactsService enContactsService;

    @Autowired
    private HuaWeiRoomService huaWeiRoomService;
    /**
    * 面试查询
    *
    * @param params 请求参数
    * @return
    */
    @GetMapping(value = "/list")
    @AutoLog("职位-面试-分页列表查询")
    @ApiOperation(value = "分页列表查询", notes = "分页列表查询")
    public Result<Page<OpInterviewHistoryVO>> list(OpInterviewHistoryParams params, HttpServletRequest request) {
        QueryWrapper<OpInterviewHistory> queryWrapper = QueryGenerator.initQueryWrapper(opInterviewHistoryConvert.toEntity(params), request.getParameterMap());
        queryWrapper.eq("del_flag", false);
        if (StringUtils.isBlank(params.getField())) {
            queryWrapper.orderByDesc("create_time");
        } else {
            queryWrapper.orderBy(true, params.getSort(), toUnderlineName(params.getField()));
        }
        SysUser sysUser = (SysUser) SubjectUtils.getSubject();
        queryWrapper.eq("user_id", sysUser.getId());
        IPage<OpInterviewHistory> page = opnterviewHistoryService.page(params.page(), queryWrapper);
        //分页结果转换器
        Function<OpInterviewHistory, OpInterviewHistoryVO> fun = opInterviewHistory -> {
            OpInterviewHistoryVO vo = new OpInterviewHistoryVO();
            vo = opInterviewHistoryConvert.toVO(opInterviewHistory);
            String jobId = vo.getJobId();
            OpJob job = jobService.getById(jobId);
            String companyId = vo.getCompanyId();
            EnInfo enInfo = enInfoService.getById(companyId);
            EnInfoVO enInfoVO = enInfoConvert.toVO(enInfo);
            OpJobVO jobVO = opJobConvert.toVO(job);
            vo.setOpJob(jobVO);
            vo.setEnInfo(enInfoVO);
            return vo;
        };

        return Result.ok((Page)page.convert(fun));
    }

    /**
    * 根据id查询
    *
    * @param id 数据id
    * @return
    */
    @GetMapping(value = "/queryById")
    @ApiOperation(value = "根据id查询", notes = "根据id查询")
    public Result<OpInterviewHistoryVO> queryById(String id) {
        OpInterviewHistory opInterviewHistory = opnterviewHistoryService
            .lambdaQuery()
            .eq(OpInterviewHistory::getId,id)
            .eq(OpInterviewHistory::getDelFlag,false)
            .one();
        if(opInterviewHistory == null){
            throw new JeecgBootException("数据不存在");
        }
        OpInterviewHistoryVO vo = opInterviewHistoryConvert.toVO(opInterviewHistory);
        String jobId = vo.getJobId();
        OpJob job = jobService.getById(jobId);
        String companyId = vo.getCompanyId();
        EnInfo enInfo = enInfoService.getById(companyId);
        EnInfoVO enInfoVO = enInfoConvert.toVO(enInfo);
        OpJobVO jobVO = opJobConvert.toVO(job);
        vo.setOpJob(jobVO);
        vo.setEnInfo(enInfoVO);
        String contactId = opInterviewHistory.getContactId();
        if (StrUtil.isNotBlank(contactId)){
            EnContacts byId = enContactsService.getById(contactId);
            if (null != byId){
                vo.setContactName(byId.getUserName());
                vo.setContactPhone(byId.getPhone());
                vo.setLocation(byId.getInterviewAddr());
            }
        }
        if (StrUtil.isNotBlank(vo.getRoomId())) {
            ConferenceRoom conferenceRoom = conferenceRoomService.getById(vo.getRoomId());
            vo.setInternetUrl(conferenceRoom.getPlayerUrl());
        }
        return Result.ok(vo);
    }

    @Autowired
    private IConferenceRoomService conferenceRoomService;
    /**
    * 面试添加
    *
    * @param params 请求参数
    * @return
    */
    @PostMapping(value = "/add")
    @AutoLog("职位-面试-添加")
    @ApiOperation(value = "添加", notes = "添加")
    public Result<?> add(@RequestBody @Valid OpInterviewHistoryParams params) {

        SysUser sysUser = (SysUser) SubjectUtils.getSubject();
        OpInterviewHistory opInterviewHistory = opInterviewHistoryConvert.toEntity(params);
        opInterviewHistory.setCreateBy(sysUser.getId());
        opInterviewHistory.setCreateTime(DateUtil.date());
        opInterviewHistory.setDelFlag(false);

        boolean saved = opnterviewHistoryService.save(opInterviewHistory);
        return saved ? Result.ok() : Result.error("添加失败");
    }
    /**
     * 接收或者拒绝面试邀请
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/acceptInview")
    public Result<?> addInview(@RequestBody @Valid OpInviewAddParams params) {

        SysUser sysUser = (SysUser) SubjectUtils.getSubject();
        OpInterviewHistory byId = opnterviewHistoryService.getById(params.getInviewId());
        if (byId.getDelFlag().equals(true)){
            return Result.error("修改失败");
        }
        if (!sysUser.getId().equals(byId.getUserId())){
            return Result.error("参数错误");
        }
        // 面试时间
        if (byId.getType() == 1) {
            //视频面试验证面试结束时间是否已过
            Date time = byId.getInterviewEndTime();
            if(DateUtil.compare(new Date(),time) > 0){
                return Result.error("面试时间已过！");
            }
        }
        if (byId.getType() == 0) {
            //线下面试验证面试开始时间是否已过
            if(DateUtil.compare(new Date(), byId.getTime()) > 0){
                return Result.error("面试时间已过！");
            }
        }


        String jobId = byId.getJobId();
        OpJob opJob = jobService.getById(jobId);
        if (params.getState() == 1){
            newsUtil.creatNews(opJob.getCreateBy(),sysUser.getId(),1,0,byId.getId(),"4");
            Map<String, String> map = emailUtil.creatEmail(opJob.getCreateBy(), sysUser.getId(), 1, 0, byId.getId(), "4");
            PiInfo piInfo = piInfoService.lambdaQuery().eq(PiInfo::getUserId, opJob.getCreateBy()).eq(PiInfo::getDelFlag, false).one();
            if (null != piInfo){
                String[] mobile1=new String[]{piInfo.getPhone()};
                sysSmsTemplateService.sendSms(mobile1,map.get("content"));
            }

        }else {
            newsUtil.creatNews(opJob.getCreateBy(),sysUser.getId(),1,0,byId.getId(),"3");
            Map<String, String> map = emailUtil.creatEmail(opJob.getCreateBy(), sysUser.getId(), 1, 0, byId.getId(), "3");
            PiInfo piInfo = piInfoService.lambdaQuery().eq(PiInfo::getUserId, opJob.getCreateBy()).eq(PiInfo::getDelFlag, false).one();
            if (null != piInfo){
                String[] mobile1=new String[]{piInfo.getPhone()};
                sysSmsTemplateService.sendSms(mobile1,map.get("content"));
            }

        }
        //

        byId.setOutLineState(params.getState());
        byId.setDoTime(new Date());
        boolean saved = opnterviewHistoryService.saveOrUpdate(byId);
        if(saved && params.getState() == 1 && byId.getType() == 1){
            // 接受视频面试 加入到创建会议室队列
        }
        return saved ? Result.ok() : Result.error("修改失败");
    }



    /**
    * 编辑
    *
    * @param params 请求参数
    * @return
    */
    @PostMapping(value = "/edit")
    @AutoLog("职位-面试-编辑")
    @ApiOperation(value = "编辑", notes = "编辑")
    @RequiresPermissions("opInterviewHistory:edit")
    public Result<?> edit(@RequestBody @Valid OpInterviewHistoryParams params) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        OpInterviewHistory opInterviewHistory = opInterviewHistoryConvert.toEntity(params);
        opInterviewHistory.setUpdateBy(sysUser.getId());
        opInterviewHistory.setUpdateTime(DateUtil.date());

        boolean updated = opnterviewHistoryService.updateById(opInterviewHistory);
        return updated ? Result.ok() : Result.error("编辑失败");
    }


    /**
    * 批量删除
    *
    * @param id 数据id
    * @return
    */
    @GetMapping(value = "/delete")
    @AutoLog("职位-面试-批量删除")
    @ApiOperation(value = "批量删除", notes = "批量删除")
    @RequiresPermissions("opInterviewHistory:delete")
    public Result delete(String[] id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LambdaUpdateWrapper<OpInterviewHistory> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.in(OpInterviewHistory::getId, id)
            .set(OpInterviewHistory::getDelFlag, true)
            .set(OpInterviewHistory::getUpdateBy, sysUser.getUsername())
            .set(OpInterviewHistory::getUpdateTime, DateUtil.date());

        boolean deleted = opnterviewHistoryService.update(updateWrapper);
        return deleted ? Result.ok() : Result.error("删除失败");
    }

    /**
    * 属性值是否重复
    *
    * @return
    */
    @Override
    @GetMapping("/propertyRepeat")
    @ApiOperation(value = "属性值是否重复", notes = "属性值是否重复")
    public Result propertyIsRepeat(@Valid AttributesValueParams params) {
        return super.propertyIsRepeat(params);
    }

    /**
    * 导出excel
    *
    * @param request
    * @param params
    */
    @SneakyThrows
    @GetMapping(value = "/exportXls")
    @ApiOperation(value = "导出excel", notes = "导出excel")
    public Result exportXls(HttpServletRequest request, OpInterviewHistoryParams params) {
        OpInterviewHistory opInterviewHistory = opInterviewHistoryConvert.toEntity(params);
        opInterviewHistory.setDelFlag(false);
        QueryWrapper<OpInterviewHistory> queryWrapper = QueryGenerator.initQueryWrapper(opInterviewHistory, request.getParameterMap());
        List<OpInterviewHistory> data = opnterviewHistoryService.list(queryWrapper);
        ExportParams exportParams = new ExportParams("职位-面试", "职位-面试");
        String url = super.exportXls(exportParams, OpInterviewHistoryVO.class,opInterviewHistoryConvert.toVO(data));
        return Result.ok((Object) url);
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @PostMapping(value = "/importExcel")
    @ApiOperation(value = "通过excel导入数据", notes = "通过excel导入数据")
        public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, OpInterviewHistory.class);
    }

}
